import { useCallback, useEffect, useMemo, useState } from 'react'
import { Select, SelectProps } from 'antd'

import { apiGetAddressList, IAddressListReq, Response as IAddressItem } from './api'

export interface AddressSelectProps extends Omit<SelectProps, 'options'> {
  /** 地址类型 1.海运港口 2.空运机场 3.铁路站点 4.集货仓 5.中转仓 */
  addressType: IAddressListReq['addressType']
  /** 自定义 label 渲染（可选） */
  labelRenderer?: (item: IAddressItem) => React.ReactNode
}

/**
 * AddressSelect
 * - 可用于 Form.Item 的受控组件（支持 value/onChange）
 * - 传入 addressType 自动拉取对应地址列表
 */
export const AddressSelect = (props: AddressSelectProps) => {
  const { addressType, labelRenderer, ...rest } = props
  const [loading, setLoading] = useState(false)
  const [options, setOptions] = useState<SelectProps['options']>([])

  const toLabel = useCallback(
    (item: IAddressItem): React.ReactNode => {
      if (labelRenderer) return labelRenderer(item)
      // 默认展示：中文名/英文名/代码（优先级）
      return item.chineseName || item.englishName || item.code || ''
    },
    [labelRenderer],
  )

  const toOption = useCallback(
    (item: IAddressItem) => ({
      label: toLabel(item),
      value: item.addressId ?? item.code ?? '',
      // 透传原始项，供 onChange 的 option 使用
      item,
    }),
    [toLabel],
  )

  const fetchList = useCallback(async () => {
    if (!addressType) {
      setOptions([])
      return
    }
    setLoading(true)
    try {
      const data = await apiGetAddressList({ addressType })
      setOptions((data || []).map(toOption))
    } finally {
      setLoading(false)
    }
  }, [addressType, toOption])

  useEffect(() => {
    fetchList()
  }, [fetchList])

  const filterOption = useMemo(() => {
    return (input: string, option?: { label?: React.ReactNode }) => {
      const labelText = String(option?.label ?? '')
      return labelText.toLowerCase().includes(input.toLowerCase())
    }
  }, [])

  return (
    <Select
      {...rest}
      options={options}
      loading={loading}
      showSearch
      optionFilterProp="label"
      filterOption={filterOption}
      allowClear={rest.allowClear ?? true}
    />
  )
}

export default AddressSelect
